/*
 * @Description: webpack配置
 * @Author bianpengfei
 * @create 2021/3/21 17:48
 */
require('./public/config.js')
const fs = require('fs')
const path = require('path')
const webpack = require('webpack')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const forElementUI = require('webpack-theme-color-replacer/forElementUI')
const ThemeColorReplacer = require('webpack-theme-color-replacer')
const WindiCSSWebpackPlugin = require('windicss-webpack-plugin')
const setting = require('./src/setting')

const { IS_PRO, ROOT_PATH } = require('./tools/utils.js')

const publicPath = IS_PRO ? '/fr/pc-template/' : '/'

const { proxy } = global.$config

/**
 * 动态的插入ejs html
 * @type {{css: *[], external: string[], title: string, script: string[]}}
 */
const inject = {
  external: {
    vue: 'Vue',
    vuex: 'Vuex',
    'vue-router': 'VueRouter',
    axios: 'axios',
    'element-ui': 'ELEMENT',
    'pikaz-excel-js': 'PikazJsExcel'
    // '@bianpengfei/utils': 'bUtils',
    // echarts: 'echarts',
  },
  minify: false, // 是否压缩html
  gzip: false, // 是否开启gzip
  script: [
    'https://npm.elemecdn.com/vue@2.6.11/dist/vue.min.js',
    'https://npm.elemecdn.com/vuex@3.4.0/dist/vuex.min.js',
    'https://npm.elemecdn.com/vue-router@3.5.3/dist/vue-router.min.js',
    'https://npm.elemecdn.com/element-ui@2.15.6/lib/index.js',
    'https://npm.elemecdn.com/axios@0.21.1/dist/axios.min.js',
    'https://npm.elemecdn.com/pikaz-excel-js@0.2.16/lib/PikazJsExcel.umd.min.js'
    // 'https://unpkg.com/@bianpengfei/utils@1.0.8/dist/b-utils.min.js'
  ],
  css: [],
  dll: [], // dll
  title: 'vue3.x后台模版'
}

module.exports = {
  devServer: {
    hot: true,
    port: 4001,
    open: false,
    hotOnly: true,
    compress: true,
    overlay: {
      warnings: true,
      errors: true
    },
    proxy: Object.values(proxy).reduce((pre, cur) => ({ ...pre, [cur['prefix']]: cur['rule'] }), {})
  },
  publicPath,
  productionSourceMap: false,
  css: {
    extract: IS_PRO,
    sourceMap: !IS_PRO // 是否开启 CSS source map  这里开发环境下开启
  },

  lintOnSave: false,

  // 第三方插件配置
  pluginOptions: {
    'style-resources-loader': {
      preProcessor: 'scss',
      patterns: [
        path.resolve(ROOT_PATH, './src/libs/style/app/variables.scss'),
        path.resolve(ROOT_PATH, './src/libs/style/app/mixin.scss')
      ]
    }
  },

  chainWebpack: (config) => {
    if (IS_PRO) {
      config.set('externals', inject.external)

      if (process.argv.includes('--report')) {
        config.plugin('bundleAnalyzerPlugin').use(BundleAnalyzerPlugin)
      }

      config.optimization.minimizer('terser').tap((args) => {
        // args[0].terserOptions.compress.drop_console = false
        return args
      })

      config.plugin('html').tap((args) => {
        args[0].script = inject.script
        args[0].css = inject.css
        args[0].title = inject.title
        args[0].minify = inject.minify
        return args
      })
    }

    config.resolve.alias
      .set('@', path.resolve(ROOT_PATH, 'src'))
      .set('@libs', path.resolve(ROOT_PATH, 'src/libs'))
      .set('@root', path.resolve(ROOT_PATH))
      .set('@assets', path.resolve(ROOT_PATH, 'src/libs/assets'))
      .set('@components', path.resolve(ROOT_PATH, 'src/components'))
      .set('@base', path.resolve(ROOT_PATH, 'src/components/base'))
      .set('@business', path.resolve(ROOT_PATH, 'src/components/business'))
      .set('@views', path.resolve(ROOT_PATH, 'src/views'))

    config.resolve.symlinks(true) // 修复HMR
    config.plugins.delete('prefetch')

    config.module.rules.delete('svg') // 重点:删除默认配置中处理svg,
    config.module
      .rule('svg-sprite-loader')
      .test(/\.svg$/)
      .include.add(path.resolve(ROOT_PATH, 'src/libs/assets/svg')) // 处理svg目录
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: '[name]'
      })
      .end()
      .use('md')
      .loader(path.resolve(ROOT_PATH, './tools/md-loader/index.js'))
      .end()
      .end()
      .rule('vue')
      .use('vue-loader')
      .tap((options) => {
        options.compiler = require('vue-template-babel-compiler')
        return options
      })

    config
      .plugin('windiCSSWebpackPlugin')
      .use(WindiCSSWebpackPlugin)
      .end()
      .plugin('themeColorReplacer')
      .use(ThemeColorReplacer, [
        {
          // 生成仅包含颜色的替换样式（主题色等）
          fileName: 'css/theme-colors.[contenthash:8].css',
          matchColors: [
            ...forElementUI.getElementUISeries(setting.primaryColor) // element-ui主色系列
          ],
          changeSelector: forElementUI.changeSelector
        }
      ])
      .end()
      .plugin('definePlugin')
      .use(webpack.DefinePlugin, [
        {
          PUBLIC_URL: JSON.stringify(String(publicPath)) // 所有加载js文件动态前缀
        }
      ])
      .end()
      .plugin('providePlugin')
      .use(webpack.ProvidePlugin, [
        {
          _: 'lodash-es',
          BUtils: '@bianpengfei/utils'
        }
      ])

    // config.optimization.splitChunks({
    //   chunks: 'all',
    //   cacheGroups: {
    //     libs: {
    //       name: 'node-modules',
    //       test: /[\\/]node_modules[\\/]/,
    //       priority: 10,
    //       chunks: 'initial' // only package third parties that are initially dependent
    //     }
    //   }
    // })
  },

  configureWebpack: (config) => {}
}
